package com.fenghuajueli.libbasecoreui.utils

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.IntRange
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.compose.LifecycleResumeEffect
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.fenghuajueli.libbasecoreui.baseswitch.PublicFunction
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyUtils
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyV3Helper
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo
import com.fenghuajueli.libbasecoreui.user.UserInfoUtils
import com.fenghuajueli.module_route.UserModuleRoute
import com.sy.lib_base_ad.AdErrorEnum
import com.sy.lib_base_ad.IAdListener
import com.sy.lib_base_ad.SimpleAdListener
import com.sy.module_ad_switch_manager.AdShowHelper
import com.sy.module_ad_switch_manager.AdSwitchManger
import com.sy.module_ad_switch_manager.listener.IPayEventCallback

object AdUtil {
    private val module: HashMap<Int, Boolean> = HashMap()

    /**
     * 验证当前position是否看了广告
     */
    @JvmStatic
    fun checkIsWatchAd(position: Int): Boolean = true == module[position]

    /**
     * 付费或广告弹窗
     */
    @JvmStatic
    fun funcInterceptor(activity: FragmentActivity, position: Int = 1, doSomething: () -> Unit) {
        countClick(activity, position) {
            if (checkIsWatchAd(position)) {
                doSomething.invoke()
                return@countClick
            }
            if (UserInfoUtils.getInstance().isVip || PublicFunction.checkIsCanFreeUseByFunPosition(position)) {
                doSomething.invoke()
                return@countClick
            }
            AdShowHelper.payEvent(
                SwitchKeyUtils.getPayStatus(),
                UserInfoUtils.getInstance().isVip,
                activity,
                object : SimpleAdListener() {
                    override fun onAdLoadError(errorCode: AdErrorEnum, errorMessage: String?) {
                        super.onAdLoadError(errorCode, errorMessage)
                        LogUtils.dTag("弹窗广告加载失败", errorMessage)
                        ToastUtils.showShort("广告加载异常~")
                    }

                    override fun onAdClose() {
                        super.onAdClose()
                        if (checkIsWatchAd(position)) {
                            doSomething.invoke()
                        } else {
                            ARouter.getInstance().build(UserModuleRoute.USER_OPEN_VIP_ACTIVITY)
                                .navigation()
                        }
                    }

                    override fun onVideoComplete() {
                        super.onVideoComplete()
                        module[position] = true
                    }

                    override fun onAdReward(rewardValue: String?, bundle: Bundle?) {
                        super.onAdReward(rewardValue, bundle)
                        module[position] = true
                    }
                },
                AdSwitchManger.adConfig?.rewardVideoId ?: "",
                "${System.currentTimeMillis()}",
                object : IPayEventCallback {
                    override fun onGotoBuyVip() {
                        ARouter.getInstance().build(UserModuleRoute.USER_OPEN_VIP_ACTIVITY).navigation()
                    }

                    override fun onCloseDialog() {
                    }

                    override fun onNormalExecute() {
                        doSomething.invoke()
                    }
                })
        }
    }

    //统计点击事件
    @JvmStatic
    fun countClick(activity: FragmentActivity, position: Int, block: (() -> Unit)? = null) {
        AdShowHelper.adEvent(
            UserInfoUtils.getInstance().isVip,
            SwitchKeyV3Helper.getAdSwitch(),
            position,
            "${System.currentTimeMillis()}",
            activity,
            object : SimpleAdListener() {
                override fun onAdClose() {
                    super.onAdClose()
                    block?.invoke()
                }

                override fun onAdLoadError(errorCode: AdErrorEnum, errorMessage: String?) {
                    super.onAdLoadError(errorCode, errorMessage)
                    block?.invoke()
                }

                override fun onVideoError() {
                    super.onVideoError()
                    block?.invoke()
                }
            })
    }

    /**
     * 统计点击事件和付费
     * adPosition 广告统计事件
     * payPosition 为-1 不卡付费
     */
    @JvmStatic
    fun clickAdAndPay(activity: FragmentActivity, adPosition: Int, payPosition: Int = adPosition, block: (() -> Unit)? = null) {
        AdShowHelper.adEvent(
            UserInfoUtils.getInstance().isVip,
            SwitchKeyV3Helper.getAdSwitch(),
            adPosition,
            "${System.currentTimeMillis()}",
            activity,
            object : SimpleAdListener() {
                private fun invokeBlockIfAllowed() {
                    if (payPosition == -1 || PublicFunction.checkCanUsedByPosition(payPosition, true)) {
                        block?.invoke()
                    }
                }

                override fun onAdClose() {
                    super.onAdClose()
                    invokeBlockIfAllowed()
                }

                override fun onAdLoadError(errorCode: AdErrorEnum, errorMessage: String?) {
                    super.onAdLoadError(errorCode, errorMessage)
                    invokeBlockIfAllowed()
                }

                override fun onVideoError() {
                    super.onVideoError()
                    invokeBlockIfAllowed()
                }
            }
        )
    }

    /**
     * 激励模式关闭，走原卡付费逻辑
     *
     */
    @JvmStatic
    fun clickPayOrAdWithIncentiveMode(activity: FragmentActivity, position: Int = 1, doSomething: () -> Unit) {
        val payState = SwitchKeyUtils.getPayStatus()
        val vipState = UserInfoUtils.getInstance().isVip
        val adSwitch = SwitchKeyV3Helper.getAdSwitch()
        val rewardId = AdSwitchManger.getIncentiveId()//这里激励视频ID需要兼容V4广告自定义渠道的ID
        val tag = "${System.currentTimeMillis()}"
        val adCallback = object : SimpleAdListener() {
            override fun onAdLoadError(errorCode: AdErrorEnum, errorMessage: String?) {
                if (errorCode == AdErrorEnum.AD_UNSATISFIED_SHOW) {
                    showToast("不满足广告加载")
                    doSomething()
                    module[position] = false
                } else {
                    ToastUtils.showShort("广告加载异常~")
                }
            }

            override fun onAdClose() {
                if (checkIsWatchAd(position)) {
                    doSomething()
                    module[position] = false
                }
            }

            override fun onAdReward(rewardValue: String?, bundle: Bundle?) {
                module[position] = true
            }

            override fun onVideoComplete() {
                super.onVideoComplete()
                module[position] = true
            }
        }
        val eventCallback = object : IPayEventCallback {
            override fun onGotoBuyVip() {
                ARouter.getInstance().build(UserModuleRoute.USER_OPEN_VIP_ACTIVITY).navigation()
            }

            override fun onCloseDialog() {
            }

            override fun onNormalExecute() {
                doSomething()
                module[position] = false
            }
        }

        AdShowHelper.incentiveModeEvent(
            payState = payState,
            vipState = vipState,
            adSwitch = adSwitch,
            activity = activity,
            rewardId = rewardId,
            tag = tag,
            adCallback = adCallback,
            eventCallback = eventCallback,
            onNoIncentiveMode = {
                showToast("激励模式关闭,走原有卡付费")
                funcInterceptor(
                    activity = activity,
                    position = position,
                    doSomething = doSomething
                )
            },
            onDialogShowBefore = {
                showToast("弹窗显示前,先走广告点击事件")
                AdShowHelper.adEvent(vipState, adSwitch, position, tag, activity, null)
            }
        )
    }

    /**
     * 激励模式关闭，走原有广告点击事件
     *
     */
    @JvmStatic
    fun clickAdAndPayWithIncentiveMode(activity: FragmentActivity, adPosition: Int, payPosition: Int = adPosition, doSomething: () -> Unit) {
        val payState = SwitchKeyUtils.getPayStatus()
        val vipState = UserInfoUtils.getInstance().isVip
        val adSwitch = SwitchKeyV3Helper.getAdSwitch()
        val rewardId = AdSwitchManger.getIncentiveId()//这里激励视频ID需要兼容V4广告自定义渠道的ID
        val tag = "${System.currentTimeMillis()}"
        val adCallback = object : SimpleAdListener() {
            override fun onAdLoadError(errorCode: AdErrorEnum, errorMessage: String?) {
                if (errorCode == AdErrorEnum.AD_UNSATISFIED_SHOW) {
                    showToast("不满足广告加载")
                    doSomething()
                    module[adPosition] = false
                } else {
                    ToastUtils.showShort("广告加载异常~")
                }
            }

            override fun onAdClose() {
                if (checkIsWatchAd(adPosition)) {
                    doSomething()
                    module[adPosition] = false
                }
            }

            override fun onAdReward(rewardValue: String?, bundle: Bundle?) {
                module[adPosition] = true
            }

            override fun onVideoComplete() {
                super.onVideoComplete()
                module[adPosition] = true
            }
        }
        val eventCallback = object : IPayEventCallback {
            override fun onGotoBuyVip() {
                ARouter.getInstance().build(UserModuleRoute.USER_OPEN_VIP_ACTIVITY).navigation()
            }

            override fun onCloseDialog() {
            }

            override fun onNormalExecute() {
                doSomething()
            }
        }

        AdShowHelper.incentiveModeEvent(
            payState = payState,
            vipState = vipState,
            adSwitch = adSwitch,
            activity = activity,
            rewardId = rewardId,
            tag = tag,
            adCallback = adCallback,
            eventCallback = eventCallback,
            onNoIncentiveMode = {
                showToast("激励模式关闭,走原有广告点击事件")
                clickAdAndPay(
                    activity = activity,
                    adPosition = adPosition,
                    payPosition = payPosition,
                    block = doSomething
                )
            },
            onDialogShowBefore = {
                showToast("激励模式弹窗显示前,先走广告点击事件")
                AdShowHelper.adEvent(vipState, adSwitch, adPosition, tag, activity, null)
            }
        )
    }

    //显示信息流广告
    @JvmStatic
    @JvmOverloads
    fun showInformationAd(
        activity: FragmentActivity,
        container: FrameLayout,
        tag: String = activity.localClassName,
        widthDp: Float = SizeUtils.px2dp(activity.resources.displayMetrics.widthPixels.toFloat()).toFloat(),
        heightDp: Float = 0f
    ) {
        AdShowHelper.showInformationAd(
            UserInfoUtils.getInstance().isVip,
            SwitchKeyV3Helper.getAdSwitch(),
            activity,
            container,
            "InformationAd_$tag",
            widthDp,
            heightDp,
            null
        )
    }

    //显示Banner广告
    @JvmStatic
    @JvmOverloads
    fun showBannerAd(
        activity: FragmentActivity,
        container: FrameLayout,
        tag: String = activity.localClassName,
        widthDp: Float = SizeUtils.px2dp(activity.resources.displayMetrics.widthPixels.toFloat()).toFloat(),
        heightDp: Float = SizeUtils.px2dp(activity.resources.displayMetrics.widthPixels * 75 / 300f).toFloat(),
    ) {
        AdShowHelper.showBannerAd(
            UserInfoUtils.getInstance().isVip,
            SwitchKeyV3Helper.getAdSwitch(),
            activity,
            container,
            "BannerAd_$tag",
            widthDp,
            heightDp,
            null
        )
    }

    @JvmStatic
    fun showBannerAdWith300X45(
        activity: FragmentActivity,
        container: FrameLayout,
        tag: String = activity.localClassName,
    ) {
        val widthDp: Float = SizeUtils.px2dp(activity.resources.displayMetrics.widthPixels.toFloat()).toFloat()
        val heightDp: Float = SizeUtils.px2dp(activity.resources.displayMetrics.widthPixels * 45 / 300f).toFloat()
        AdShowHelper.showBannerAd(
            UserInfoUtils.getInstance().isVip,
            SwitchKeyV3Helper.getAdSwitch(),
            activity,
            container,
            "BannerAd_$tag",
            widthDp,
            heightDp,
            null
        )
    }

    @JvmStatic
    fun showBannerAdWith300X75(
        activity: FragmentActivity,
        container: FrameLayout,
        tag: String = activity.localClassName,
    ) {
        val widthDp: Float = SizeUtils.px2dp(activity.resources.displayMetrics.widthPixels.toFloat()).toFloat()
        val heightDp: Float = SizeUtils.px2dp(activity.resources.displayMetrics.widthPixels * 75 / 300f).toFloat()
        AdShowHelper.showBannerAd(
            UserInfoUtils.getInstance().isVip,
            SwitchKeyV3Helper.getAdSwitch(),
            activity,
            container,
            "BannerAd_$tag",
            widthDp,
            heightDp,
            null
        )
    }

    //观看广告点击事件(根据点击次数)
    @JvmStatic
    fun View.clickWatchAd(
        @IntRange(from = 1, to = 5) position: Int,
        block: (v: View) -> Unit
    ) {
        setOnClickListener { v ->
            (this.context as? FragmentActivity)?.let { countClick(it, position) { block(v) } }
                ?: run {
                    showToast("广告点击类型转换错误")
                    block(v)
                }
        }
    }

    //广告付费弹窗事件
    @JvmStatic
    fun View.clickPayOrAd(
        @IntRange(from = 1, to = 5) position: Int,
        block: (v: View) -> Unit
    ) {
        setOnClickListener { v ->
            if (QuickClickUtils.isFastClick()) {
                return@setOnClickListener
            }
            (this.context as? FragmentActivity)?.let { funcInterceptor(it, position) { block(v) } }
                ?: run {
                    showToast("广告点击类型转换错误")
                    block(v)
                }
        }
    }

    @JvmStatic
    fun View.clickPayOrAdWithIncentiveMode(
        @IntRange(from = 1, to = 5) position: Int,
        block: (v: View) -> Unit
    ) {
        setOnClickListener { v ->
            (this.context as? FragmentActivity)?.let { clickPayOrAdWithIncentiveMode(it, position) { block(v) } }
                ?: run {
                    showToast("广告点击类型转换错误")
                    block(v)
                }
        }
    }

    //统计点击事件和付费
    @JvmStatic
    fun View.clickAdAndPay(
        adPosition: Int,
        payPosition: Int = adPosition,
        block: (v: View) -> Unit
    ) {
        setOnClickListener { v ->
            (this.context as? FragmentActivity)?.let { clickAdAndPay(it, adPosition, payPosition) { block(v) } }
                ?: run {
                    showToast("广告点击类型转换错误")
                    block(v)
                }
        }
    }

    @JvmStatic
    fun View.clickAdAndPayWithIncentiveMode(
        adPosition: Int,
        payPosition: Int = adPosition,
        block: (v: View) -> Unit
    ) {
        setOnClickListener { v ->
            (this.context as? FragmentActivity)?.let { clickAdAndPayWithIncentiveMode(it, adPosition, payPosition) { block(v) } }
                ?: run {
                    showToast("广告点击类型转换错误")
                    block(v)
                }
        }
    }

    private fun showToast(msg: String) {
        if (AppConfigInfo.APP_DEBUG) {
            ToastUtils.showShort(msg)
        }
    }
}

@Composable
fun BannerAdView(
    modifier: Modifier = Modifier,
    adContainer: FrameLayout? = null,
    tag: String = "",
    adListener: IAdListener = SimpleAdListener()
) {
    val context = LocalContext.current
    val _adContainer = adContainer.takeIf { it != null } ?: remember { FrameLayout(context) }

    LifecycleResumeEffect(key1 = Unit) {
        val vipState = UserInfoUtils.getInstance().isVip
        val adSwitch = SwitchKeyV3Helper.getAdSwitch()
        if (vipState) {
            _adContainer.removeAllViews()
        }
        require(context is FragmentActivity) {
            "展示广告的Activity父类必须为FragmentActivity"
        }
        AdShowHelper.showBannerAd(
            vipState = vipState,
            adSwitch = adSwitch,
            activity = context,
            container = _adContainer,
            tag = "BannerAdView_$tag",
            listener = adListener
        )
        onPauseOrDispose { }
    }

    AndroidView(modifier = modifier.fillMaxWidth(), factory = {
        _adContainer.apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            setBackgroundColor(Color.WHITE)
        }
    })
}

@Composable
fun BannerAdView(
    modifier: Modifier = Modifier,
    adContainer: FrameLayout? = null,
    tag: String = "",
    adListener: IAdListener = SimpleAdListener(),
    widthDp: Float,
    heightDp: Float,
) {
    val context = LocalContext.current
    val _adContainer = adContainer.takeIf { it != null } ?: remember { FrameLayout(context) }

    LifecycleResumeEffect(key1 = Unit) {
        val vipState = UserInfoUtils.getInstance().isVip
        val adSwitch = SwitchKeyV3Helper.getAdSwitch()
        if (vipState) {
            _adContainer.removeAllViews()
        }
        require(context is FragmentActivity) {
            "展示广告的Activity父类必须为FragmentActivity"
        }
        AdShowHelper.showBannerAd(
            vipState = vipState,
            adSwitch = adSwitch,
            activity = context,
            container = _adContainer,
            tag = "BannerAdView_$tag",
            widthDp = widthDp,
            heightDp = heightDp,
            listener = adListener
        )
        onPauseOrDispose { }
    }

    AndroidView(modifier = modifier.fillMaxWidth(), factory = {
        _adContainer.apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            setBackgroundColor(Color.WHITE)
        }
    })
}

@Composable
fun InformationAdView(
    modifier: Modifier = Modifier,
    adContainer: FrameLayout? = null,
    tag: String = "",
    adListener: IAdListener = SimpleAdListener()
) {
    val context = LocalContext.current
    val _adContainer = adContainer.takeIf { it != null } ?: remember { FrameLayout(context) }

    LifecycleResumeEffect(key1 = Unit) {
        val vipState = UserInfoUtils.getInstance().isVip
        val adSwitch = SwitchKeyV3Helper.getAdSwitch()
        if (vipState) {
            _adContainer.removeAllViews()
        }
        require(context is FragmentActivity) {
            "展示广告的Activity父类必须为FragmentActivity"
        }
        AdShowHelper.showInformationAd(
            vipState = vipState,
            adSwitch = adSwitch,
            activity = context,
            container = _adContainer,
            tag = "InformationAdView_$tag",
            listener = adListener
        )
        onPauseOrDispose { }
    }

    AndroidView(modifier = modifier.fillMaxWidth(), factory = {
        _adContainer.apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            setBackgroundColor(Color.WHITE)
        }
    })
}

/**
 * 统计点击事件和付费
 * adPosition 广告统计事件
 * payPosition 为-1 不卡付费
 */
@Stable
fun Modifier.clickAdAndPay(
    context: Context,
    adPosition: Int,
    payPosition: Int = adPosition,
    onClick: () -> Unit
) = this.clickable {
    (context as? FragmentActivity)?.let { AdUtil.clickAdAndPay(it, adPosition, payPosition) { onClick() } }
        ?: run {
            if (AppConfigInfo.APP_DEBUG) {
                ToastUtils.showShort("广告点击类型转换错误")
            }
            onClick()
        }
}

@Stable
fun Modifier.clickAdAndPayWithIncentiveMode(
    context: Context,
    adPosition: Int,
    payPosition: Int = adPosition,
    onClick: () -> Unit
) = this.clickable {
    (context as? FragmentActivity)?.let { AdUtil.clickAdAndPayWithIncentiveMode(it, adPosition, payPosition) { onClick() } }
        ?: run {
            if (AppConfigInfo.APP_DEBUG) {
                ToastUtils.showShort("广告点击类型转换错误")
            }
            onClick()
        }
}

@Stable
fun Modifier.clickPayOrAd(
    context: Context,
    position: Int,
    onClick: () -> Unit
) = this.clickable {
    (context as? FragmentActivity)?.let { AdUtil.funcInterceptor(it, position) { onClick() } }
        ?: run {
            if (AppConfigInfo.APP_DEBUG) {
                ToastUtils.showShort("广告点击类型转换错误")
            }
            onClick()
        }
}

@Stable
fun Modifier.clickPayOrAdWithIncentiveMode(
    context: Context,
    position: Int,
    onClick: () -> Unit
) = this.clickable {
    (context as? FragmentActivity)?.let { AdUtil.clickPayOrAdWithIncentiveMode(it, position) { onClick() } }
        ?: run {
            if (AppConfigInfo.APP_DEBUG) {
                ToastUtils.showShort("广告点击类型转换错误")
            }
            onClick()
        }
}